//
//  CurtainControllView.m
//  Test
//
//  Created by jingyao on 2017/12/15.
//  Copyright © 2017年 jingyao. All rights reserved.
//

#import "CurtainControllView.h"
#import "Global.h"

@interface CurtainControllView()

@property (weak, nonatomic) IBOutlet UIImageView *controllImageView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *showWidthConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *controllCenterXConstraint;

@end

@implementation CurtainControllView

+ (instancetype)createViewFromXIB {
    CurtainControllView *controllView = [[NSBundle mainBundle] loadNibNamed:@"CurtainControllView" owner:self options:nil][0];
    [controllView setRate:cRate];
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:controllView action:@selector(panAction:)];
    [controllView.controllImageView setUserInteractionEnabled:YES];
    [controllView.controllImageView addGestureRecognizer:pan];
    
    return controllView;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        
    }
    return self;
}

//每次页面发生变化都会调用的方法
- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextBeginPath(context);
    CGContextSetLineWidth(context, 2.0);
    CGContextSetStrokeColorWithColor(context, [UIColor grayColor].CGColor);

    //第一个刻度点
    CGPoint point1 = CGPointMake((self.frame.size.width - 30)/4 * 0 + 15 + 1, self.frame.size.height/2);
    CGContextMoveToPoint(context, point1.x, point1.y);
    CGContextAddLineToPoint(context, point1.x, point1.y - 5);
    
    //第二个刻度点
    CGPoint point2 = CGPointMake((self.frame.size.width - 30)/4 * 1 + 15, self.frame.size.height/2);
    CGContextMoveToPoint(context, point2.x, point2.y);
    CGContextAddLineToPoint(context, point2.x, point2.y - 5);
    
    //第三个刻度点
    CGPoint point3 = CGPointMake((self.frame.size.width - 30)/4 * 2 + 15, self.frame.size.height/2);
    CGContextMoveToPoint(context, point3.x, point3.y);
    CGContextAddLineToPoint(context, point3.x, point3.y - 5);
    
    //第四个刻度点
    CGPoint point4 = CGPointMake((self.frame.size.width - 30)/4 * 3 + 15, self.frame.size.height/2);
    CGContextMoveToPoint(context, point4.x, point4.y);
    CGContextAddLineToPoint(context, point4.x, point4.y - 5);
    
    //第五个刻度点
    CGPoint point5 = CGPointMake((self.frame.size.width - 30)/4 * 4 + 15 - 1, self.frame.size.height/2);
    CGContextMoveToPoint(context, point5.x, point5.y);
    CGContextAddLineToPoint(context, point5.x, point5.y - 5);

    CGContextStrokePath(context);
}

//rate : [0, 1]
- (void)setRate:(CGFloat)rate {
    self.showWidthConstraint.constant = (self.frame.size.width - 30) * rate;
    self.controllCenterXConstraint.constant = -self.frame.size.width/2 + 15 + (self.frame.size.width - 30) * rate;
}

#pragma mark 拖拽事件
- (void)panAction:(UIPanGestureRecognizer *)gesture {
    UIImageView *imageView = (UIImageView *)gesture.view;
    
    switch (gesture.state) {
        case UIGestureRecognizerStatePossible:
            [imageView setTranslatesAutoresizingMaskIntoConstraints:YES];
            break;
            
        case UIGestureRecognizerStateBegan:
            break;
            
        case UIGestureRecognizerStateChanged:{
            CGPoint velocityEndDirection = [gesture velocityInView:self];//速率
            if (velocityEndDirection.x > 0) {
                //向右滑动
                if (self.changingUpRateBlock) {
                    self.changingUpRateBlock(YES);
                }
            } else if (velocityEndDirection.x < 0) {
                //向左滑动
                if (self.changingUpRateBlock) {
                    self.changingUpRateBlock(NO);
                }
            } else {
                //不变
            }
            
            CGPoint touchPoint = [gesture locationInView:self];
            CGFloat moveX = touchPoint.x;
            NSLog(@"moveX = %f", moveX);
            
            if (moveX < 15) {
                moveX = 15;
            } else if (moveX > self.frame.size.width - 15) {
                moveX = self.frame.size.width - 15;
            }
            
            imageView.center = CGPointMake(moveX, self.center.y);
            CGFloat rate = (moveX - 15) / (self.frame.size.width - 30);
            [self setRate:rate];
        }
            break;
            
        case UIGestureRecognizerStateEnded: {
            //每个刻度之间的距离
            CGFloat deltaX = (self.frame.size.width - 30)/4;
            //第一个刻度点
            CGPoint point1 = CGPointMake((self.frame.size.width - 30)/4 * 0 + 15 + 1, self.frame.size.height/2);
            //第二个刻度点
            CGPoint point2 = CGPointMake((self.frame.size.width - 30)/4 * 1 + 15, self.frame.size.height/2);
            //第三个刻度点
            CGPoint point3 = CGPointMake((self.frame.size.width - 30)/4 * 2 + 15, self.frame.size.height/2);
            //第四个刻度点
            CGPoint point4 = CGPointMake((self.frame.size.width - 30)/4 * 3 + 15, self.frame.size.height/2);
            //第五个刻度点
            CGPoint point5 = CGPointMake((self.frame.size.width - 30)/4 * 4 + 15 - 1, self.frame.size.height/2);
            CGFloat rate = 0.0f;
            if (fabs(imageView.center.x - point1.x) <= deltaX/2) {
                rate = 0.0f;
            } else if (fabs(imageView.center.x - point2.x) <= deltaX/2) {
                rate = 1/4.0f;
            } else if (fabs(imageView.center.x - point3.x) <= deltaX/2) {
                rate = 2/4.0f;
            } else if (fabs(imageView.center.x - point4.x) <= deltaX/2) {
                rate = 3/4.0f;
            } else if (fabs(imageView.center.x - point5.x) <= deltaX/2) {
                rate = 1.0f;
            }
            
            [self setRate:rate];
            
            //在这里把rate转换成数字，请求网络接口
            NSInteger number = 99 * rate;
            
            //[self requestToWriteCurtainStatusWithValue:number];
            [self setAllTenantBlindWithValue:number];
            //[self setAll22fBlindWithValue:number];
            NSLog(@"请求写设备状态接口发送的integer值是：%ld", (long)number);

            if (self.changedRateBlock) {
                self.changedRateBlock(rate);
            }
            
            [imageView setTranslatesAutoresizingMaskIntoConstraints:NO];
        }
            break;
            
        case UIGestureRecognizerStateCancelled:
            break;
            
        case UIGestureRecognizerStateFailed:
            break;
            
        default:
            break;
    }
}

#pragma mark - 网络请求方法
- (void)requestToWriteCurtainStatusWithValue:(NSInteger)value {
    NSURL *url = [NSURL URLWithString:@"http://192.168.98.95:8099/api/setDevicePropertyValue"];
    NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url];
    mRequest.HTTPMethod = @"POST";
    
    NSString *idStr = [NSString stringWithFormat:@"5a40624802ca8a43eeaff1e8"];
    NSInteger valueInt = value;
    NSNumber *valueNum = @(valueInt);
    NSMutableDictionary *bodyDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:idStr, @"id", valueNum, @"value", nil];
    NSArray *bodyArray = @[bodyDict];
    NSLog(@"打印bodyarray是:%@", bodyArray);
    //NSData *bodyData = [NSKeyedArchiver archivedDataWithRootObject:bodyArray];
    NSData *bodyData = [NSJSONSerialization dataWithJSONObject:bodyArray
                                                   options:NSJSONWritingPrettyPrinted
                                                     error:nil];
    mRequest.HTTPBody = bodyData;
    //NSLog(@"bodydata是：%@", bodyData);
    //NSLog(@"body的string模式是:%@", [[NSString alloc] initWithData:bodyData encoding:NSUTF8StringEncoding]);
    [mRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:mRequest completionHandler:
                                      ^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                                          
                                          if (error) {
                                              NSLog(@"error是:%@", error);
                                              return ;
                                          }
                                          //NSLog(@"response是：%@", response);
                                          NSLog(@"data是：%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
                                          
                                          NSError *jsonError;
                                          NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error: &jsonError];
                                          
                                          if (jsonError) {
                                              NSLog(@"数据转换出错了，jsonError是：%@", jsonError);
                                              return;
                                          }
                                          
                                          NSInteger code = [[dataDic objectForKey:@"code"] integerValue];
                                          if (code == 0) {
                                              NSArray *resultArray = [dataDic objectForKey:@"result"];
                                              
                                              if (resultArray.count == 0) {
                                                  NSLog(@"result数组返回为空，不能继续");
                                                  return;
                                              }
                                              
                                              NSDictionary *tempDic = resultArray[0];
                                              NSInteger code2 = [[tempDic objectForKey:@"code"] integerValue];
                                              if (code2 == 100) {
                                                  NSLog(@"第二个code正确，写设备状态请求成功");
                                                  //更新全局变量
                                                  cRate = value/99.0f;
                                              }else {
                                                  NSLog(@"第二个code不是101，是:%ld", (long)code2);
                                              }
                                          }else {
                                              NSLog(@"第一个code不是0，code是：%ld", (long)code);
                                              //显示提示错误的hud
                                          }
                                      }];
    [dataTask resume];
}

//只控制所有tenant账号的窗帘请求(tenant账号使用)
- (void)setAllTenantBlindWithValue:(NSInteger)value {
    NSString *httpStr = [NSString stringWithFormat:@"http://172.105.198.110:8099/api/setAllTenantBlind"];
    NSString *str1 = [httpStr stringByAppendingString:@"?value="];
    NSString *str2 = [str1 stringByAppendingString:[NSString stringWithFormat:@"%ld", (long)value]];
    NSURL *url = [NSURL URLWithString:str2];
    NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url];
    mRequest.HTTPMethod = @"GET";
    NSString *authValue = [NSString stringWithFormat:@"Bearer %@", [Global getToken]];
    [mRequest setValue:authValue forHTTPHeaderField:@"Authorization"];
    [mRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:mRequest completionHandler:
                                      ^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                                          
                                          if (error) {
                                              NSLog(@"只控制所有tenant账号的窗帘请求(tenant账号使用)error是:%@", error);
                                              return ;
                                          }
                                          //NSLog(@"response是：%@", response);
                                          NSLog(@"只控制所有tenant账号的窗帘请求(tenant账号使用)data是：%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
                                          
                                          NSError *jsonError;
                                          NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error: &jsonError];
                                          
                                          if (jsonError) {
                                              NSLog(@"只控制所有tenant账号的窗帘请求(tenant账号使用)数据转换出错了，jsonError是：%@", jsonError);
                                              return;
                                          }
                                          
                                          NSInteger code = [[dataDic objectForKey:@"code"] integerValue];
                                          if (code == 0) {
                                              //成功
                                          }else {
                                              NSLog(@"只控制所有tenant账号的窗帘请求(tenant账号使用)第一个code不是0，code是：%ld", (long)code);
                                              //显示提示错误的hud
                                          }
                                      }];
    [dataTask resume];
}

//只控制所有22层的窗帘请求(fm账号使用)
- (void)setAll22fBlindWithValue:(NSInteger)value {
    NSString *httpStr = [NSString stringWithFormat:@"http://172.105.198.110:8099/api/setAll22fBlind"];
    NSString *str1 = [httpStr stringByAppendingString:@"?value="];
    NSString *str2 = [str1 stringByAppendingString:[NSString stringWithFormat:@"%ld", (long)value]];
    NSURL *url = [NSURL URLWithString:str2];
    NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url];
    mRequest.HTTPMethod = @"GET";
    NSString *authValue = [NSString stringWithFormat:@"Bearer %@", [Global getToken]];
    [mRequest setValue:authValue forHTTPHeaderField:@"Authorization"];
    [mRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:mRequest completionHandler:
                                      ^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                                          
                                          if (error) {
                                              NSLog(@"只控制所有22层的窗帘请求(fm账号使用)error是:%@", error);
                                              return ;
                                          }
                                          //NSLog(@"response是：%@", response);
                                          NSLog(@"只控制所有22层的窗帘请求(fm账号使用)data是：%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
                                          
                                          NSError *jsonError;
                                          NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error: &jsonError];
                                          
                                          if (jsonError) {
                                              NSLog(@"只控制所有22层的窗帘请求(fm账号使用)数据转换出错了，jsonError是：%@", jsonError);
                                              return;
                                          }
                                          
                                          NSInteger code = [[dataDic objectForKey:@"code"] integerValue];
                                          if (code == 0) {
                                              //成功
                                          }else {
                                              NSLog(@"只控制所有22层的窗帘请求(fm账号使用)第一个code不是0，code是：%ld", (long)code);
                                              //显示提示错误的hud
                                          }
                                      }];
    [dataTask resume];
}
@end
